package com.ibiaoke.order.service;

import com.google.common.collect.Lists;
import com.ibiaoke.common.base.Page;
import com.ibiaoke.common.consts.CommonConsts;
import com.ibiaoke.common.utils.AssertUtils;
import com.ibiaoke.goods.dao.GoodsDao;
import com.ibiaoke.goods.dao.XcxGoodsDao;
import com.ibiaoke.goods.dao.XcxShopPriceDao;
import com.ibiaoke.goods.entity.Goods;
import com.ibiaoke.goods.entity.XcxGoods;
import com.ibiaoke.goods.entity.XcxShopPrice;
import com.ibiaoke.goods.entity.XcxShopPriceExample;
import com.ibiaoke.order.dao.ShoppingCartDao;
import com.ibiaoke.order.entity.ShoppingCart;
import com.ibiaoke.order.entity.ShoppingCartExample;
import com.ibiaoke.order.entity.ShoppingCartGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

/**
 * Created by Biaoke on 2017/6/26.
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartDao shoppingCartDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private XcxGoodsDao xcxGoodsDao;
    @Autowired
    private XcxShopPriceDao xcxShopPriceDao;
    @Autowired
    private GoodsRushService goodsRushService;
    @Autowired
    private ShoppingCartGoodsService shoppingCartGoodsService;


    /**
     * 根据客户Id、商品Id查询购物车
     *
     * @param goodsId
     * @param customerId
     * @return
     */
    @Override
    public ShoppingCart getShoppingCartByCustomerId(Integer goodsId, Integer customerId) {
//        return shoppingCartDao.getShoppingCartByCustomerId(goodsId, customerId);
        return null;
    }

    /**
     * 根据购物车Id、商品Id查询购物车
     *
     * @param cartId
     * @param customerId
     * @return
     */
    @Override
    public ShoppingCart getShoppingCartByCartId(Integer cartId, Integer customerId) {
        return shoppingCartDao.getShoppingCartByCartId(cartId, customerId);
    }

    /**
     * 添加购物车
     *
     * @param
     * @param shopId
     * @return
     */
    @Override
    public int saveShoppingService(Integer customerId, Integer shopId, Integer goodsId, Integer num) {
        AssertUtils.notNull(customerId, "用户Id不能为空");
        AssertUtils.notNull(shopId, "店铺Id不能为空");
        AssertUtils.notNull(goodsId, "商品Id不能为空");

        Goods goods = goodsDao.getGoods(goodsId, shopId);
        AssertUtils.requireTrue(CommonConsts.NO == goods.getDelStatus(), "商品不存在");
        AssertUtils.requireTrue(CommonConsts.YES == goods.getStatus(), "商品已经下架");
        AssertUtils.requireTrue(goods.getStockNum() > 0, "商品库存不足");

        ShoppingCart shoppingCart = getShoppingCartByCustomerId(goodsId, customerId);

        if (null != shoppingCart) {
            num += shoppingCart.getNum();
            AssertUtils.requireTrue(goods.getStockNum() > num, "该商品库存不足");
            AssertUtils.requireTrue(num > 0, "商品数量不能小于0");
            goodsRushService.validateCount2(goods, num, customerId, false);
            return shoppingCartDao.updateShoppingCart(shoppingCart.getCartId(), customerId, num);
        } else {
            AssertUtils.requireTrue(goods.getStockNum() > num, "该商品库存不足");
            AssertUtils.requireTrue(num > 0, "商品数量不能小于0");

            ShoppingCart shoppingCartNew = new ShoppingCart();
            shoppingCartNew.setGoodsId(goodsId);
            shoppingCartNew.setNum(num);
            shoppingCartNew.setShopId(shopId);
            shoppingCartNew.setCuntomerId(customerId);
            shoppingCartNew.setDelStatus((byte) CommonConsts.NO);
            shoppingCartNew.setCreateTime(new Date());
            shoppingCartNew.setUpdateTime(new Date());
            goodsRushService.validateCount2(goods, num, customerId, false);
            return shoppingCartDao.insertSelective(shoppingCartNew);
        }
    }

    /**
     * 获取购物车列表
     *
     * @param customerId
     * @param shopId
     * @return
     */
    @Override
    public List<ShoppingCart> listShoppingCart(Integer customerId, Integer shopId) {
        AssertUtils.notNull(customerId, "客户Id不能为空");

        List<ShoppingCart> shoppingCartLists = shoppingCartDao.getShoppingCartByCustomerId(customerId);

        fillGoods(shoppingCartLists, shopId);

        //抢购价
        shoppingCartLists.forEach(shoppingCart -> goodsRushService.validateCount(
                shoppingCart.getGoods()
                ,shoppingCart.getNum(),
                customerId,
                false));
        return shoppingCartLists;
    }

    @Override
    public void fillGoods(List<ShoppingCart> shoppingCartLists, Integer shopId) {
        List<Integer> ids = Lists.newArrayList();
        for (ShoppingCart shoppingCart : shoppingCartLists) {
            ids.add(shoppingCart.getGoodsId());
        }
        List<Goods> goodsList = goodsDao.listByIds(ids, shopId);

        shoppingCartLists.forEach(shoppingCart -> goodsList.forEach(goods -> {
            if (Objects.equals(goods.getGoodsId(), shoppingCart.getGoodsId())) {
                shoppingCart.setGoods(goods);
            }
        }));
    }

    /**
     * (可批量)删除购物车
     *
     * @param cartId
     * @param customerId
     * @return
     */
    @Override
    public int batchDeleteShoppingCart(String cartId, Integer customerId) {
        ShoppingCartExample example = new ShoppingCartExample();
        List<Integer> shoppingCartlist = new ArrayList<>();

        AssertUtils.notBlank(cartId, "购物车编号不能为空");
        String[] array = cartId.split(",");

        for (int i = 0; i < array.length; i++) {
            shoppingCartlist.add(Integer.parseInt(array[i]));
        }
        return shoppingCartDao.batchDeleteShoppingCart(shoppingCartlist, customerId);
    }


    /**
     * 购物车数量
     *
     * @param customerId
     * @return
     */
    @Override
    public Long getShoppingCartNum(Integer customerId) {
        List<ShoppingCart> shoppingCarts = shoppingCartDao.getShoppingCartByCustomerId(customerId);
        long sum = shoppingCarts.stream().mapToInt(ShoppingCart::getNum).sum();
        return sum;
    }
/**************************************************新版微商城_____购物车**************************************************************/
    @Override
    public void newSaveShoppingCart(Integer customerId, Integer shopId, Integer goodsId, Integer num) {

        AssertUtils.notNull(customerId, "用户Id不能为空");
        AssertUtils.notNull(shopId, "店铺Id不能为空");
        AssertUtils.notNull(goodsId, "商品Id不能为空");

        XcxGoods xcxGoods = xcxGoodsDao.getXcxGoodsByGoodsId(goodsId, shopId);
        AssertUtils.requireTrue(CommonConsts.NO == xcxGoods.getDelStatus(), "商品不存在");
        AssertUtils.requireTrue(CommonConsts.YES == xcxGoods.getStatus(), "商品已经下架");

        //获取该店铺下此商品的价格库存
        XcxShopPriceExample example = new XcxShopPriceExample();
        example.createCriteria().andShopIdEqualTo(shopId).andGoodsIdEqualTo(goodsId);
        XcxShopPrice xcxShopPrice = xcxShopPriceDao.getByExample(example);

        AssertUtils.requireTrue(num > 0, "商品数量不能小于0");
        Double stockNum = Double.parseDouble( xcxShopPrice.getSpec().toString()) * num;
        AssertUtils.requireTrue(xcxShopPrice.getStockNum()>stockNum,"该商品库存不足");

        //判断此店铺商品加过购物车
        ShoppingCart shoppingCart =  shoppingCartDao.getShaoppingCartInfo(customerId, shopId, goodsId );
        if (null != shoppingCart) {
            ShoppingCartGoods shoppingCartGoods = shoppingCartGoodsService.getGoodsInfos(shoppingCart.getCartId(), goodsId, shopId);
            if (null != shoppingCartGoods) {
                num = shoppingCartGoods.getNum() + num;
                shoppingCartGoodsService.updateShoppingCartGoods(shoppingCart.getCartId(), goodsId, shopId, num);
            }
        } else {
            ShoppingCart shoppingCartNew = new ShoppingCart();
            shoppingCartNew.setGoodsId(goodsId);
            shoppingCartNew.setShopId(shopId);
            shoppingCartNew.setCuntomerId(customerId);
            shoppingCartNew.setDelStatus((byte) CommonConsts.NO);
            shoppingCartNew.setCreateTime(new Date());
            shoppingCartNew.setUpdateTime(new Date());
            Integer count = shoppingCartDao.insertSelective(shoppingCartNew);
            if (count > 0) {
                ShoppingCart shopCart = shoppingCartDao.getShaoppingCartInfo(shoppingCartNew.getCuntomerId(), shoppingCartNew.getShopId(), shoppingCartNew.getGoodsId());
                ShoppingCartGoods cartGoods = new ShoppingCartGoods();
                cartGoods.setShoppingcartId(shopCart.getCartId());
                cartGoods.setGoodsId(goodsId);
                cartGoods.setGoodsName(xcxGoods.getName());
                cartGoods.setGoodsImage(xcxGoods.getImage());
                cartGoods.setGoodsPrice(xcxShopPrice.getPrice());
               // cartGoods.setGoodsSpec(xcxShopPrice.getSpec());
                cartGoods.setShopId(shopId);
                cartGoods.setNum(num);
                cartGoods.setDelStatus((byte) CommonConsts.NO);
                cartGoods.setCreatetime(new Date());
                cartGoods.setUpdatetime(new Date());
                shoppingCartGoodsService.saveNewInfo(cartGoods);
            }
        }
    }

    @Override
    public Integer newDeleteShopppingCart(Integer customerId,String cartId) {
        AssertUtils.notBlank(cartId, "购物车ID不能为空");

        List<Integer> shoppingCartlist = new ArrayList<>();
        String[] array = cartId.split(",");

        for (int i = 0; i < array.length; i++) {
            shoppingCartlist.add(Integer.parseInt(array[i]));
        }
        List<ShoppingCart> shoppingCarts = shoppingCartDao.getShoppingCartInfos(shoppingCartlist, customerId);

        shoppingCarts.forEach(shoppingCart -> {
            shoppingCartGoodsService.deleteShopppingCartGoods(shoppingCart.getCartId());
        });
        return shoppingCartDao.batchDeleteShoppingCart(shoppingCartlist, customerId);
    }

    @Override
    public List<ShoppingCart> newListShoppingCart(Integer customerId, Page page) {
        List<ShoppingCart> shoppingCartList = shoppingCartDao.getShoppingCartByCustomerId(customerId,page);
        List<Integer> cartIds = Lists.newArrayList();
        List<Integer> shopIds = Lists.newArrayList();
        shoppingCartList.forEach(shoppingCart -> {
            cartIds.add(shoppingCart.getCartId());
        });
        shoppingCartList.forEach(shoppingCart -> {
            shopIds.add(shoppingCart.getShopId());
        });
        List<ShoppingCartGoods> shoppingCartGoodsList = shoppingCartGoodsService.listCartGoods(cartIds, shopIds);

        shoppingCartList.forEach(shoppingCart -> shoppingCartGoodsList.forEach(shoppingCartGoods -> {
            if (Objects.equals(shoppingCart.getCartId(), shoppingCartGoods.getShoppingcartId()) && Objects.equals(shoppingCart.getShopId(), shoppingCartGoods.getShopId())) {
                shoppingCart.setShoppingCartGoods(shoppingCartGoods);
            } }
        ));
        //shoppingCartList.stream().collect(groupingBy(ShoppingCart::getShopId));

        return shoppingCartList;
    }

    @Override
    public Integer updateCartGoodsNum(ShoppingCartGoods shoppingCartGoods) {
        AssertUtils.notNull(shoppingCartGoods.getShoppingcartId(),"购物车ID不能为空");
        AssertUtils.notNull(shoppingCartGoods.getGoodsId(),"商品ID不能为空");
        AssertUtils.notNull(shoppingCartGoods.getShopId(),"店铺ID不能为空");
        return shoppingCartGoodsService.updateNum(shoppingCartGoods.getShoppingcartId(), shoppingCartGoods.getGoodsId(), shoppingCartGoods.getShopId(), shoppingCartGoods.getNum());
    }

    @Override
    public Integer getShoppingCartNumber(Integer customerId) {
        List<ShoppingCart> shoppingCarts = shoppingCartDao.getShoppingCartByCustomerId(customerId);
        List<Integer> Ids = new ArrayList<>();
        shoppingCarts.forEach(shoppingCart -> {
            Ids.add(shoppingCart.getCartId());
        });
        List<ShoppingCartGoods> shoppingCartGoods = shoppingCartGoodsService.getShoppingCartByCartId(Ids);
        Integer sum = shoppingCartGoods.stream().mapToInt(ShoppingCartGoods::getNum).sum();
        return sum;
    }
}
